<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>贷款计算</title>
    <style>
      body {
        margin: 0;
        padding: 2rem;
        font-size: 1rem;
      }
      .tab {
        display: flex;
        margin-bottom: 1rem;
      }
      h2 {
        margin: 0 auto 20px;
      }
      h3 {
        cursor: pointer;
        margin-right: 10px;
      }
      .current {
        color: red;
      }
      .item {
        display: flex;
        line-height: 2;
        margin-bottom: 10px;
        align-items: center;
      }
      label {
        width: 100px;
        font-weight: bold;
      }
      input,
      select {
        flex: 1;
        padding: 1rem;
        box-sizing: border-box;
      }
      input {
        width: 276px;
      }
      span {
        padding-left: 5px;
      }
      .button {
        padding: 1rem;
        margin-top: 2rem;
        background-color: #f03131;
        color: #ffffff;
        text-align: center;
        border-radius: 5px;
        cursor: pointer;
      }
      .zongjia,
      .jijin,
      .zonge {
        display: none;
      }
      .resultWrap {
        display: none;
        position: absolute;
        left: 2rem;
        right: 2rem;
        top: 2rem;
        border: 1px solid #ffd7a8;
        padding: 1.5rem;
        border-radius: 5px;
        background: #fff8f0;
      }
      .resultTab {
        display: flex;
        margin-bottom: 10px;
      }
      .resultTab div {
        margin: 0 10px;
        cursor: pointer;
      }
      .resultTab div.active {
        color: red;
      }
      .perMonth {
        font-size: 30px;
        font-weight: bold;
        margin: 10px 0 0;
      }
      .topWrap {
        padding: 30px;
        background: #f11e04;
        color: #fff;
        text-align: center;
        border-radius: 10px;
        margin-bottom: 10px;
      }
      .zixun {
        text-align: right;
        margin-bottom: 10px;
        font-size: 14px;
        color: #eee;
      }
      .listWrap {
        display: flex;
        justify-content: space-between;
        color: #fff;
        margin-top: 30px;
      }
      .list {
        margin: 0 5px;
      }
      .list div {
      }
      .list p {
        margin: 0;
        font-size: 16px;
      }
      .finalResult {
        padding-top: 10px;
        padding-left: 10px;
        max-height: 260px;
        overflow-y: auto;
        background: #fff;
        border-radius: 10px;
      }
      .table {
        width: 100%;
        font-size: 13px;
        border-collapse: collapse;
      }
      th {
        position: sticky;
        top: 0;
        background: #d8d8d8;
        text-align: left;
        padding-left: 10px;
      }
      td {
        padding-left: 10px;
      }
      tbody tr:nth-of-type(even) {
        background: #d8d8d8;
      }
      .more {
        font-size: 14px;
      }
      .close {
        position: absolute;
        right: 1rem;
        top: 1rem;
      }
      .close2 {
        display: block;
        width: 50%;
        margin: 2rem auto 0;
        padding: 1rem;
        background: #f03131;
        border-radius: 5px;
        color: #ffffff;
        text-align: center;
      }
    </style>
  </head>

  <body>
    <h1>贷款计算</h1>
    <div class="tab">
      <h3 class="current" id="shangye">商业贷款</h3>
      <h3 id="zuhe">组合贷款</h3>
      <h3 id="gongjijin">公积金贷款</h3>
    </div>
    <div>
      <div class="item">
        <label>计算方式</label>
        <select id="fangshi">
          <option value="0">按贷款总额</option>
          <option value="1">按房屋总价</option>
        </select>
      </div>
      <!-- 房屋总价 -->
      <div class="zongjia">
        <div class="item">
          <label>房屋总价</label>
          <input type="number" placeholder="0" class="houseMoney" />
          <span>万</span>
        </div>
        <div class="item">
          <label>贷款比例</label>
          <input type="number" placeholder="6.5" value="6.5" id="loanScale" />
          <span>成</span>
        </div>
      </div>
      <!-- 房屋总价 -->
      <div class="zonge">
        <div class="item">
          <label>贷款总额</label>
          <input type="number" placeholder="0" class="loanTotal" />
          <span>万</span>
        </div>
      </div>
      <!-- 公积金贷款 -->
      <div class="jijin">
        <div class="item">
          <label>公积金金额</label>
          <input type="number" placeholder="0" id="fundMoney" />
          <span>万</span>
        </div>
        <div class="item">
          <label>公积金年限</label>
          <select id="gongYear"></select>
        </div>
        <div class="item">
          <label>公积金套数</label>
          <select id="gongTaoshu">
            <option value="0">首套</option>
            <option value="1">二套</option>
          </select>
        </div>
        <div class="item">
          <label>公积金利率</label>
          <select id="gonglilv">
            <option value="3.1">基准利率（3.1%）</option>
            <option value="2.6">基准利率（2.6%）</option>
          </select>
        </div>
      </div>
      <!-- 公积金贷款 -->
      <!-- 商业贷款 -->
      <div class="shangdai">
        <div class="item">
          <label>商贷金额</label>
          <input type="number" placeholder="0" id="businessMoney" />
          <span>万</span>
        </div>
        <div class="item">
          <label>商贷年限</label>
          <select id="shangYear">
            <!-- <option value="25年">25年</option> -->
          </select>
        </div>
        <div class="item">
          <label>利率方式</label>
          <input type="text" value="按最新LPR" disabled />
        </div>
        <div class="item">
          <label>LPR</label>
          <input type="number" placeholder="4.65" id="lpr" />
          <span>%</span>
        </div>
        <div class="item">
          <label>购房套数</label>
          <select id="houseNum">
            <option value="0">首套</option>
            <option value="1">二套</option>
          </select>
        </div>
        <div class="item">
          <label>基点</label>
          <input type="number" placeholder="30" id="basicPoint" />
          <span>BP(‱)</span>
        </div>
        <div class="item">
          <label>商贷利率</label>
          <input
            type="text"
            placeholder="4.65%+30‱=4.95%"
            id="totalLPR"
            disabled
          />
          <!-- <span>%</span> -->
        </div>
      </div>
      <!-- 商业贷款 -->
    </div>
    <div class="button">开始计算</div>
    <div class="resultWrap">
      <h2>房贷计算结果</h2>
      <span class="close">关闭</span>
      <div class="resultTab">
        <div class="active">等额本息</div>
        <div>等额本金</div>
      </div>
      <div class="topWrap">
        <!-- <div class="zixun">详细咨询></div> -->
        <div class="title">每月应还</div>
        <p class="perMonth">暂无</p>
        <div class="more"></div>
        <div class="listWrap">
          <div class="list">
            <div>贷款总额</div>
            <p class="totalLoan">暂无</p>
          </div>
          <div class="list">
            <div>利息总额</div>
            <p class="totalInterest">暂无</p>
          </div>
          <div class="list">
            <div>贷款年限</div>
            <p class="totalYear">暂无</p>
          </div>
        </div>
      </div>
      <div class="finalResult">
        <table class="table"></table>
      </div>
      <span class="close2">关闭</span>
    </div>
    <script src="js/jquery-3.5.1.js"></script>
    <script type="module">
      import { buildParameter, calculate } from "./js/loanCalculateUtil.js";

      let baseUrl = "https://rht.jfzh.com.cn/",
        // var baseUrl = "http://10.10.100.136:443/",
        TabCur = 0, //当前标签,默认商业贷款
        TabOn = 0, //当前标签,默认商业贷款
        yearArr = [
          "1年",
          "2年",
          "3年",
          "4年",
          "5年",
          "6年",
          "7年",
          "8年",
          "9年",
          "10年",
          "11年",
          "12年",
          "13年",
          "14年",
          "15年",
          "16年",
          "17年",
          "18年",
          "19年",
          "20年",
          "21年",
          "22年",
          "23年",
          "24年",
          "25年",
          "26年",
          "27年",
          "28年",
          "29年",
          "30年",
        ],
        lpr = 4.65,
        LPR_Greater5Year = null,
        LPR_Less5Year = null,
        basicPoint = null,
        totalLPR = null,
        LPR_ErTao = null,
        LPR_ShouTao = null,
        fundInterestArr = ['2.6', '3.1'], //公积金利率
        accumulationFundLoanRatio = 3.25,
        yearindex = 24,
        fundindex = 24,
        fundNumindex= 0,
        businessMoney = null, //商贷金额
        fundMoney = null, //公积金金额
        fangshiVal = 0, //计算方式
        loanScale = $("#loanScale").val(); //默认贷款比例

      $(".houseMoney").blur(function () {
        $("#businessMoney,.loanTotal").val($(this).val() * (loanScale / 10));
      });
      $("#loanScale").blur(function () {
        $("#businessMoney,.loanTotal").val(
          ($(".houseMoney").val() * $(this).val()) / 10
        );
      });
      $("#fundMoney").blur(function () {
        fundMoney = $(this).val();
        $("#businessMoney").val($(".loanTotal").val() - fundMoney);
      });
      $("#basicPoint").blur(function () {
        basicPoint = $(this).val();
        totalLPR = parseFloat(lpr) + parseFloat(basicPoint / 100);
        // console.log(lpr)
        // console.log(basicPoint)
        $("#totalLPR").val(`${lpr}%+${basicPoint}‱=${totalLPR}%`);
      });
      $("#lpr").blur(function () {
        lpr = $(this).val();
        // console.log(lpr)
        // console.log(basicPoint)
        totalLPR = parseFloat(lpr) + parseFloat(basicPoint / 100);
        $("#totalLPR").val(`${lpr}%+${basicPoint}‱=${totalLPR}%`);
      });
      getCurrentLPR(); //调取接口获得最新LPR

      //商业贷款、公积金贷款年限
      let yearHtml = "";
      yearArr.forEach((el, i) => {
        yearHtml += `<option value="${i + 1}">${el}</option>`;
      });
      $("#gongYear,#shangYear").html(yearHtml);
      $("#gongYear,#shangYear").val(25); //默认贷款年限

      $(".tab").on("click", "h3", function () {
        TabCur = $(this).index();

        $("#businessMoney").val("0");
        $(".title").html("每月应还");
        $(".table,.more").html("");
        $(".perMonth,.totalLoan,.totalInterest,.totalYear").html("暂无");

        $(this).addClass("current").siblings().removeClass("current");
        if (TabCur == 0) {
          $(".shangdai").show();
          $(".jijin,.zonge").hide();
        } else if (TabCur == 1) {
          $(".jijin,.zonge,.shangdai").show();
        } else {
          $(".jijin").show();
          $(".shangdai,.zonge").hide();
        }
      });
      $("#fangshi").change(function () {
        //计算方式
        fangshiVal = $(this).val();
        if (fangshiVal == 1) {
          $(".zongjia").show();
        } else {
          $(".zongjia").hide();
        }
      });

      $("#shangYear").change(function () {
        //商业贷款年限
        let val = $(this).val();
        // console.log(val)
        if (val > 4) {
          lpr = LPR_Greater5Year;
        } else {
          lpr = LPR_Less5Year;
        }
        yearindex = val;
        $("#lpr").val(lpr);
        $("#totalLPR").val(`${lpr}%+${basicPoint}‱=${totalLPR}%`);
      });

      $("#gongYear").change(function () {
        //公积金贷款年限
        let val = $(this).val();
        if (val < 5) {
          $("#gonglilv ").val(fundInterestArr[0])
          accumulationFundLoanRatio=fundInterestArr[0]
        } else {
          $("#gonglilv ").val(fundInterestArr[1])
          accumulationFundLoanRatio = fundInterestArr[1];
        }
        fundindex = val;
      });

       $("#gongTaoshu").change(function () {
        //公积金贷款年限
        let val = $(this).val();
        let html=`<option value="3.1">基准利率（3.1%）</option>
            <option value="2.6">基准利率（2.6%）</option>`
        if (val ==0) {
          fundNumindex=0
          fundInterestArr = ['2.6', '3.1'];
        } else {
          fundNumindex=1
          fundInterestArr = ['3.025', '3.575'];
          html=`<option value="3.575">基准利率（3.575%）</option>
            <option value="3.025">基准利率（3.025%）</option>`
        }
        $('#gonglilv').html(html)
      });

      $("#houseNum").change(function () {
        //购房套数
        let val = $(this).val();
        // console.log(val)
        if (val == 0) {
          (basicPoint = LPR_ShouTao * 100),
            (totalLPR = (LPR_ShouTao - 0 + (lpr - 0)).toFixed(2));
        } else {
          (basicPoint = LPR_ErTao * 100),
            (totalLPR = (LPR_ErTao - 0 + (lpr - 0)).toFixed(2));
        }
        $("#basicPoint").val(basicPoint);
        $("#totalLPR").val(`${lpr}%+${basicPoint}‱=${totalLPR}%`);
      });

      //开始计算
      $(".button").click(function () {
        // console.log(TabCur)
        businessMoney = $("#businessMoney").val();
        fundMoney = $("#fundMoney").val();

        if (TabCur == 0) {
          if (!businessMoney) {
            alert("请先输入商贷金额");
          }
          calculator();
        } else if (TabCur == 1) {
          if (!businessMoney) {
            alert("请先输入商贷金额");
          }
          if (!fundMoney) {
            alert("请先输入公积金贷款金额");
          }
          calculator();
        } else if (TabCur == 2) {
          if (!fundMoney) {
            alert("请先输入公积金贷款金额");
          }
          calculator();
        }
      });
      $(".resultTab").on("click", "div", function () {
        TabOn = $(this).index();
        $(this).addClass("active").siblings().removeClass("active");
        calculator();
      });
      $(".close,.close2").click(function () {
        $(".resultWrap").hide();
      });
      // 初始化利率
      function getCurrentLPR() {
        $.ajax({
          contentType: "application/json",
          type: "get",
          url: baseUrl + "lpr/GetCurrentLPR",
          cache: false,
          // data: JSON.stringify(datas), //重点必须为一个变量如：data
          dataType: "json",
          async: false,
          success: function (data) {
            // console.log(data.data);
            (LPR_Greater5Year = data.data.LPR_Greater5Year),
              (LPR_Less5Year = data.data.LPR_Less5Year),
              (lpr = data.data.LPR_Greater5Year), //初始化LPR
              (basicPoint = data.data.LPR_ShouTao * 100), //初始化basicPoint
              (totalLPR = (
                data.data.LPR_ShouTao -
                0 +
                (data.data.LPR_Greater5Year - 0)
              ).toFixed(2)), //初始化totalLPR
              (LPR_ErTao = data.data.LPR_ErTao),
              (LPR_ShouTao = data.data.LPR_ShouTao);
          },
        });
      }

      // 计算结果
      function calculator() {
        let parameter,
          conclusion,
          isPortfolioLoan,
          decreasePerMonth,
          title = "",
          html = "",
          tableHead = "<thead><tr>",
          tableBody = "<tbody>",
          heads,
          bodys,
          result;

        if (TabCur == 0) {
          parameter = buildParameter(
            "商业贷款",
            "等额本金",
            businessMoney,
            totalLPR,
            yearindex - 0 + 1,
            null,
            null,
            null
          );
        } else if (TabCur == 1) {
          parameter = buildParameter(
            "组合贷款",
            "等额本金",
            businessMoney - 0,
            totalLPR,
            yearindex - 0 + 1,
            fundMoney - 0,
            accumulationFundLoanRatio,
            fundindex - 0 + 1
          );
        } else {
          parameter = buildParameter(
            "公积金贷款",
            "等额本金",
            null,
            null,
            null,
            fundMoney,
            accumulationFundLoanRatio,
            fundindex - 0 + 1
          );
        }
        conclusion = calculate(parameter);
        console.log(conclusion);

        if (TabOn == 0) {
          result = conclusion.equivalentPrincipalAndInterest;
          title = "每月应还";
          $(".more").html(``);
        } else {
          result = conclusion.equivalentPrincipal;
          decreasePerMonth = result.decreasePerMonth;
          title = `首月应还`;
          $(".more").html(`每月少还 <b>${decreasePerMonth}</b> 元`);
        }
        heads = result.tabHeader;
        bodys = result.tabBody;

        $(".title").html(title);
        $(".perMonth").html(result.payPerMonth + "元");
        $(".totalLoan").html(result.totalLoan + "万");
        $(".totalInterest").html(result.totalInterest + "元");
        $(".totalYear").html(result.totalYear + "年");

        isPortfolioLoan = conclusion.isPortfolioLoan;

        if (!isPortfolioLoan) {
          isPortfolioLoan = false;
        }

        if (heads.length == 5) {
          bodys.forEach((el) => {
            tableBody += `<tr><td>${el.count}</td><td>${el.preLoan}</td><td>${el.principal_paid}</td><td>${el.interest}</td><td>${el.principal_left}</td></tr>`;
          });
        } else {
          bodys.forEach((el) => {
            tableBody += `<tr><td>${el.count}</td><td>${el.totalPay}</td><td>${el.comericalPay}</td><td>${el.accumulationPay}</td></tr>`;
          });
        }
        heads.forEach((el) => {
          tableHead += `<th>${el}</th>`;
        });
        tableHead += "</tr></thead>";
        tableBody += "</tbody>";
        html = tableHead + tableBody;
        $(".table").html(html);
      }
    </script>
  </body>
</html>
